package com.coin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coin.domain.AccountDetail;
import com.coin.dto.UserDto;
import com.coin.feign.SysMemberFeignClient;
import com.coin.mapper.AccountDetailMapper;
import com.coin.service.AccountDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 李力
 * @description 针对表【account_detail(资金账户流水)】的数据库操作Service实现
 * @createDate 2025-06-12 10:12:52
 */
@Service
public class AccountDetailServiceImpl extends ServiceImpl<AccountDetailMapper, AccountDetail>
        implements AccountDetailService {

    @Autowired
    private SysMemberFeignClient sysUserFeignClient;

    /**
     * @Description: 条件分页查询
     * @Author: 李 力
     * @Date: 2025/6/13
     * @Param:
     * @return: R
     */
    @Override
    public Page<AccountDetail> findByPage(Page<AccountDetail> page, Long coinId, Long userId, String userName, String mobile, Byte status, String amountStart, String amountEnd, String startTime, String endTime) {
        LambdaQueryWrapper<AccountDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(coinId != null, AccountDetail::getCoinId, coinId)
                .eq(userId != null, AccountDetail::getUserId, userId)
                .ge(StrUtil.isNotEmpty(amountStart), AccountDetail::getAmount, new BigDecimal(amountStart))
                .le(StrUtil.isNotEmpty(amountEnd), AccountDetail::getAmount, new BigDecimal(amountEnd))
                .between(StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime), AccountDetail::getCreated, startTime, endTime);
        Map<Long, UserDto> userDtoMap = new HashMap<>();
        if (userId != null || StrUtil.isNotEmpty(userName) || StrUtil.isNotEmpty(mobile)) {
            userDtoMap = sysUserFeignClient.getBasicUsers2(userId == null ? null : Collections.singletonList(userId), userName, mobile);
            if (CollectionUtil.isEmpty(userDtoMap)) {
                return page;
            }
        }
        Page<AccountDetail> rechargePage = page(page, queryWrapper);
        List<AccountDetail> records = rechargePage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            Map<Long, UserDto> finalUserDtoMap = userDtoMap;
            records.forEach(cashRecharge -> {
                cashRecharge.setUsername(finalUserDtoMap.get(cashRecharge.getUserId()).getUsername());
                cashRecharge.setRealName(finalUserDtoMap.get(cashRecharge.getUserId()).getRealName());
            });
        }
        return rechargePage.setRecords(records);
    }
}




